package com.wnhz.work.jy.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.wnhz.work.jy.BaseActivity;
import com.wnhz.work.jy.MyApplication;
import com.wnhz.work.jy.R;
import com.wnhz.work.jy.adapter.BankCardAdapter;
import com.wnhz.work.jy.bean.BankCardBean;
import com.wnhz.work.jy.utils.ConfigUtil;
import com.wnhz.work.jy.utils.xutils3.MyCallBack;
import com.wnhz.work.jy.utils.xutils3.XUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@ContentView(R.layout.activity_bank_card)
public class BankCardActivity extends BaseActivity implements AdapterView.OnItemClickListener {
    @ViewInject(R.id.view_main_middle_title)
    private TextView title;
    @ViewInject(R.id.listView)
    private ListView listView;
    private List<BankCardBean> lists = new ArrayList<>();
    private BankCardAdapter adapter;
    private String type;

    @ViewInject(R.id.include_occupied)
    private View include_occupied;
    @ViewInject(R.id.blank_img)
    private ImageView blank_img;
    @ViewInject(R.id.blank_tv)
    private TextView blank_tv;

    private String time;

    private final int FROM_ADD_CODE = 642;
    private String myBankId;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    setBlank();
                    adapter.notifyDataSetChanged();
                    break;

                default:
                    break;
            }
            super.handleMessage(msg);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        x.view().inject(this);
        type = getIntent().getStringExtra("type");
        initTirle();
        myBankId = getIntent().getStringExtra("id");

        /*for (int i = 0; i < 2; i++) {
            BankCardBean b= new BankCardBean();
            lists.add(b);
        }*/
       /* include_occupied = findViewById(R.id.include_occupied);
        blank_img = (ImageView) findViewById(R.id.blank_img);*/


        adapter = new BankCardAdapter(this, lists);
        if ("选择银行卡".equals(type)) {
            adapter.setSelect(true);
        } else {
            title.setText("银行卡");
        }


        listView.setAdapter(adapter);
        listView.setOnItemClickListener(this);

        //getData();
        setBlank();

        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {

                if (!adapter.isSelect())
                    deleteshowDialog(position);
                return false;
            }
        });

        if (myBankId != null && !"".equals(myBankId)) {
            for (int i = 0; i < lists.size(); i++) {
                if (myBankId.equals(lists.get(i).getId())) {
                    adapter.setIndex(i);
                }
            }
        }
    }

    private void deleteshowDialog(final int index) {
        /***
         这里使用了 android.support.v7.app.AlertDialog.Builder
         可以直接在头部写 import android.support.v7.app.AlertDialog
         那么下面就可以写成 AlertDialog.Builder
         */
        android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(this);
        builder.setMessage("删除银行卡？");
        builder.setNegativeButton("取消", null);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                deleteBank(index);
            }
        });
        builder.show();
    }


    private void setBlank() {
        if (lists.size() == 0) {
            blank_tv.setText("点击下方添加银行卡吧~");
            blank_img.setImageResource(R.mipmap.ic_kongyinghangka);
            include_occupied.setVisibility(View.VISIBLE);
        } else {
            include_occupied.setVisibility(View.GONE);
        }
    }

    private void initTirle() {
        if ("选择银行卡".equals(type)) {
            title.setText("选择银行卡");
        } else {
            title.setText("银行卡");
        }

    }


    @Event(value = {R.id.btn_main_left, R.id.add_card_btn})
    private void myClick(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.btn_main_left:
                finish();
                break;

            //添加银行卡
            case R.id.add_card_btn:
                intent = new Intent(this, AddBankCard.class);
                startActivity(intent);
                break;
        }
    }


    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        if ("选择银行卡".equals(type)) {
            adapter.setIndex(i);
            adapter.notifyDataSetChanged();
            Intent intent = new Intent();
            intent.putExtra("bank_mame", lists.get(i).getBankName());
            intent.putExtra("bank_card_number", lists.get(i).getBankCardNumber());
            intent.putExtra("name", lists.get(i).getUsername());
            intent.putExtra("id", lists.get(i).getId());
            intent.putExtra("branch", lists.get(i).getBranch());
            intent.putExtra("time", time);
            setResult(RESULT_OK, intent);
            finish();
        } else {

        }
    }


    private static final String TAG = "BankCardActivity";

    private void getData() {
        Map<String, Object> map = new HashMap<>();
        map.put("userId", MyApplication.getInstance().userBean.getUserId());
        showDialog();
        XUtil.Post(ConfigUtil.CASHLIST, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                System.out.println(result + "onSuccess: BankCardActivity");
                try {
                    lists.clear();
                    JSONObject jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("result");
                    time = jsonObject.optString("time");
                    JSONArray jsonArray = jsonObject.optJSONArray("banks");
                    if (jsonArray != null) {
                        for (int i = 0; i < jsonArray.length(); i++) {
                            BankCardBean bean = new BankCardBean();
                            jsonObject = jsonArray.optJSONObject(i);
                            String Id = jsonObject.optString("Id");
                            String username = jsonObject.optString("username");
                            String cardno = jsonObject.optString("cardno");
                            String bankId = jsonObject.optString("bankId");
                            String bankname = jsonObject.optString("bankname");
                            String pic = jsonObject.optString("pic");
                            String branch = jsonObject.optString("branch");

                            bean.setBankName(bankname);
                            bean.setBankCardNumber(cardno);
                            bean.setId(Id);
                            bean.setUsername(username);
                            bean.setBankId(bankId);
                            bean.setBranch(branch);
                            lists.add(bean);

                        }
                    }
                    mHandler.sendEmptyMessage(1);


                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
                closeDialog();
            }
        });
    }

    private void deleteBank(int index) {
        Map<String, Object> map = new HashMap<>();
        map.put("userId", MyApplication.getInstance().userBean.getUserId());
        map.put("bankCardNumber", lists.get(index).getBankCardNumber());
        showDialog();
        XUtil.Post(ConfigUtil.DELBANK, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                System.out.println("onSuccess: deleteBank" + result);
                try {
                    JSONObject json = new JSONObject(result);
                    String re = json.optString("result");
                    String info = json.optString("info");
                    if ("1".equals(re)) {
                        MyToast(info);
                        getData();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
                closeDialog();
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        getData();
    }
}
